import React, {Fragment, PureComponent} from 'react';
import {connect} from 'dva';
import {Button, Card, Col, Divider, Dropdown, Form, Icon, Input, Menu, Modal, Row, Select, Tree,} from 'antd';
import TableList from '@/components/TableList';
import ChoosePerson from '@/components/BindPerson/ChoosePerson';
import HasUser from '@/components/BindPerson/HasUser';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { ruleP, nameMaxLength, remarkMaxLength} from '@/utils/rule'
import styles from '../search.less';

const {TextArea} = Input;
const FormItem = Form.Item;
const {TreeNode} = Tree;
const DirectoryTree = Tree.DirectoryTree;

const CreateForm = Form.create()(props => {
  const {modalVisible, form, addDataFn, updateFn, handleModalVisible, text} = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      if (text) {
        updateFn(fieldsValue, text)
      } else {
        addDataFn(fieldsValue);
      }
    });
  };
  return (
    <Modal
      destroyOnClose
      width={640}
      title={text ? '编辑角色' : '新增角色'}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
      maskClosable={false}
    >
      <FormItem labelCol={{span: 5}} wrapperCol={{span: 19}} label="角色名称">
        {form.getFieldDecorator('roleName', {
          rules: [{required: true, message: '角色名称不能为空'},
          {pattern:new RegExp(ruleP(4)[0],'g'), message:ruleP(4)[1]},
          {max: nameMaxLength()[0], message: nameMaxLength()[1]}],
          initialValue: text && text.roleName || ''
        })(<Input placeholder="请输入"/>)}
      </FormItem>

      <FormItem labelCol={{span: 5}} wrapperCol={{span: 19}} label="角色描述">
        {form.getFieldDecorator('remark', {
          rules: [{required: true, whitespace:true, message: '角色描述不能为空'}, {max: remarkMaxLength()[0], message: remarkMaxLength()[1]}],
          initialValue: text && text.remark || ''
        })(<TextArea
          style={{minHeight: 32}}
          placeholder="请输入"
          rows={4}
        />)}
      </FormItem>
    </Modal>
  );
});


/* eslint react/no-multi-comp:0 */
@connect(({role, loading}) => ({
  role,
  loading: loading.models.role,
}))


@Form.create()
class RoleList extends PureComponent {
  state = {
    modalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    stepFormValues: {},
    text: {},
    bindUserVisible: false, //绑定用户
    treeDataList: [],//组织树
    orgDataList: [],//用户
    userInfo: {},
    authorizeModalVisible: false,
    menuTreeData: [], // 菜单树
    groupMember: [],
    // 设置人员相关
    chooseBVisible: false,
    hasUserVisible: false, //已选人员
  };

  columns = [
    {
      title: '角色名称',
      dataIndex:'roleName',
    },
    {
      title: '角色类型',
      render: (text, record) => (
        text.isDefault == 0 ? '内置' : '自定义'
      ),
    },
    {
      title: '角色描述',
      dataIndex: 'remark',
      width: '40%',
      render: (text) => (
        <div className={styles.colRemark} title={text}>
          {text}
        </div>
      )
    },
    /* {
       title: '创建时间',
       render: (text, record) => (
         moment(new Date()).format('YYYY-MM-DD HH:mm')
       ),
     },*/
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          {text.authorizeFlag == 0 ? (
            <a onClick={() => this.handleAuthorizeModalVisible(true, text)}>菜单授权</a>
          ) : null}
          {text.authorizeFlag == 0 && text.isDefault != 0? (
            <Divider type="vertical"/>
          ) : null}
          {/*普通用户角色不给选人，每个人至少一个角色*/}
          {text && (text.isDefault == 0) && (text.roleCode != 'everyonerole') ? (
            <a onClick={() => this.handChooseBVisible(true, text)}>人员设置</a>
          ) : null}

          {text && (text.isDefault != 0) && (
            <Dropdown
              overlay={
                <Menu>
                  <Menu.Item key="binduser" onClick={() => this.handChooseBVisible(true, text)}>人员设置</Menu.Item>
                  <Menu.Item key="edit" onClick={() => this.handleModalVisible(true, text)}>编辑</Menu.Item>
                  <Menu.Item onClick={() => this.deleteData(text.id)}>删除</Menu.Item>
                </Menu>
              }>
              <a>更多 <Icon type="down"/></a>
            </Dropdown>
          )}
        </Fragment>
      ),
    },
  ];

  deleteData = (id) => {
    Modal.confirm({
      title: '删除',
      content: '您确定要删除以下数据吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.handleDeleteData(id),
    });
  };

  batchDelete = (rows = []) => {
    const ids = rows.map((item) => {
      return item.id;
    }).join(",");
    this.deleteData(ids); //批量删除
  };

  // 删除方法
  handleDeleteData(id) {
    const {dispatch} = this.props;
    dispatch({
      type: 'role/remove',
      payload: {id},
      callback: (res) => {
        if (res.result == "ok") {
          Modal.success({title: res.msg});
          this.pageList();
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
  }

  // 分页查询列表
  pageList(data, pageSize = 10, pageNum = 0) {
    const {dispatch} = this.props;
    const values = {
      roleName: data && data.roleName, //数据字典名称
      isDefault: data && data.isDefault,
      pageSize: pageSize, //分页每页条数
      pageNum: pageNum, //分页页码
    };
    dispatch({
      type: 'role/queryList',
      payload: values,
    });
  }

  componentDidMount() {
    this.pageList();
    this.treeData(); // 组织树请求
    this.menuTree(); // 查询菜单树
  }

  //查询菜单树
  menuTree = () => {
    const {dispatch} = this.props;
    dispatch({
      type: 'role/menuTree',
      callback: (res) => {
        if (res.result == "ok") {
          this.setState({
            menuTreeData: res.data,
          })
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
  }

  //菜单授权
  menuRight = (param) => {
    const {dispatch} = this.props;
    dispatch({
      type: 'role/menuRight',
      payload: param,
      callback: (res) => {
        if (res.result == "ok") {
          Modal.success({title: res.msg});
          this.pageList();
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
  }

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();
    const {dispatch, form} = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      this.setState({
        formValues: fieldsValue,
      })
      //点击查询
      this.pageList(fieldsValue);
    });
  };

  // 新增弹框的显示和隐藏
  handleModalVisible = (flag, text) => {
    this.setState({
      modalVisible: !!flag,
      text: text
    });
  };

  // 菜单授权
  handleAuthorizeModalVisible = (flag, text) => {
    this.setState({
      authorizeModalVisible: !!flag,
      text: text
    });
  };

  // 更新接口
  updateFn = (fields, text) => {
    const {dispatch} = this.props;
    const params = {
      id: text.id,
      remark: fields.remark,
      roleName: fields.roleName,
    }
    dispatch({
      type: 'role/update',
      payload: params,
      callback: (res) => {
        if (res.result == "ok") {
          Modal.success({title: res.msg});
          this.pageList();
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
    this.handleModalVisible();
  };

  // 增加接口
  addDataFn = (fields) => {
    const {dispatch} = this.props;
    const params = {
      remark: fields.remark,
      roleName: fields.roleName,
    }
    dispatch({
      type: 'role/add',
      payload: params,
      callback: (res) => {
        if (res.result == "ok") {
          Modal.success({title: res.msg});
          this.pageList();
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
    this.handleModalVisible();
  };

  handleStandardTableChange(pagination, filters, sorter) {
    const {formValues} = this.state;
    // 分页请求
    this.pageList(formValues, pagination.pageSize, pagination.current - 1);
  }

   // 已选择成员详情弹框
  handleHasUserVisible = (flag) => {
    this.setState({
      hasUserVisible: !!flag,
    });
  };

  deleteGMember = (userCode) => {
    const { groupMember } = this.state;
    let copyGM = [...groupMember];
    copyGM.map((v,i) => {
      if(v.userCode == userCode) {
        copyGM.splice(i,1);
      }
    })
    this.setState({
      groupMember: copyGM,
    })
  }

   // 已选择成员详情弹框
  handChooseBVisible = (flag, userInfo) => {
    this.setState({
      chooseBVisible: !!flag,
      userInfo,
    });
    if(flag) {
      this.listForLevelSF(userInfo.id)
    }
    if(!flag) {
      this.setState({
        groupMember: [],
      })
    }
  };

  listForLevelSF = (roleId) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'role/listForRoleId',
      payload: {roleId},
      callback: (res) => {
        if(res.result == "ok") {
          this.setState({
            groupMember:res.data.dataList
          });
        }
      },
    });
  }

  // 绑定用户弹框显示和隐藏
  handleBindUserVisible = (flag, selectedRows) => {
    this.setState({
      bindUserVisible: !!flag,
    });
    if(!flag){
      const { groupMember } = this.state;
      const concatArr = selectedRows?groupMember.concat(selectedRows):groupMember;
      // 去重
      const result = [];
      let obj = {};
      for(var i =0; i<concatArr.length; i++){
         if(!obj[concatArr[i].userCode]){
            result.push(concatArr[i]);
            obj[concatArr[i].userCode] = true;
         }
      }
      this.setState({
        // personData: {},
        groupMember: result,
      })
    }
  };

  // 组织树请求
  treeData() {
    const {dispatch} = this.props;
    dispatch({
      type: 'role/getTree',
      callback: (res) => {
        if (res.result == "ok") {
          this.setState({
            treeDataList: res.data,
          })
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
  }

  //组织人员请求
  getList(res, pageSize = 5, pageNum = 0) {
    const {dispatch} = this.props;
    const values = {
      orgId: res && res.orgId,
      roleId: res && res.id || '',
      pageSize: pageSize,
      pageNum: pageNum,
      userName:res&& res.userName||'',
      userCode:res&& res.userCode||'',
    };
    dispatch({
      type: 'role/getList',
      payload: values,
      callback: (res) => {
        if (res.result == "ok") {
          this.setState({
            orgDataList: res.data,
          })
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
  }

  //绑定人员接口
  bindUserRole(params) {
    const { dispatch } = this.props;
    dispatch({
      type: 'role/bindUserRole',
      payload: params,
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({title: res.msg});
          this.handChooseBVisible()
        }else {
          Modal.error({title: '操作失败',content: res.msg});
        }
      },
    });
  }

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
  }; //重置

  renderSimpleForm() {
    const {
      form: {getFieldDecorator},
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          <Col md={8} sm={24}>
            <FormItem label="角色名称">
              {getFieldDecorator('roleName')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="角色类型">
              {getFieldDecorator('isDefault')(<Select placeholder="请选择">
                <Option value=''>全部</Option>
                <Option value={0}>内置</Option>
                <Option value={1}>自定义</Option>
              </Select>)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    const {expandForm} = this.state;
    return expandForm ? this.renderSimpleForm() : this.renderSimpleForm();
  }

  render() {
    const {
      role: {data},
      loading,
      form,
    } = this.props;
    const {selectedRows, modalVisible, stepFormValues, text, bindUserVisible, treeDataList,
      orgDataList, userInfo, authorizeModalVisible,
      menuTreeData,
      groupMember,chooseBVisible,hasUserVisible
    } = this.state;
    const menu = (
      <Menu onClick={this.handleMenuClick} selectedKeys={[]}>
        <Menu.Item key="remove">删除</Menu.Item>
      </Menu>
    );
    const parentMethods = {
      handleModalVisible: this.handleModalVisible,
      addDataFn: this.addDataFn,
      updateFn: this.updateFn
    };

    const BindUserMethods = {
      handleBindUserVisible: this.handleBindUserVisible,
      getList: this.getList.bind(this),
      bindUserRole: this.bindUserRole.bind(this),
    }
    const authorizeMethods = {
      handleAuthorizeModalVisible: this.handleAuthorizeModalVisible,
      handleAuthorize: this.handleAuthorize,
      menuRight: this.menuRight,
    };
    const BindChooBMethods = {
      handChooseBVisible: this.handChooseBVisible,
      handleHasUserVisible: this.handleHasUserVisible,
      handleBindUserVisible: this.handleBindUserVisible,
      bindUserRole: this.bindUserRole.bind(this),
    }
    const hasUserMethods = {
      handleHasUserVisible: this.handleHasUserVisible.bind(this),
      deleteGMember: this.deleteGMember.bind(this),
    }

    return (
      <PageHeaderWrapper title="角色管理">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
                新增
              </Button>
            </div>
            <TableList
              className={styles.tdPadding}
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={this.columns}
              onSelectRow={this.handleSelectRows}
              hideRowSelection={true}
              onChange={this.handleStandardTableChange.bind(this)}
              rowKey={record => record.id}
            />
          </div>
        </Card>
        <CreateForm {...parentMethods} modalVisible={modalVisible} text={text}/>
        {chooseBVisible?<ChooseButton
          {...BindChooBMethods}
          chooseBVisible={chooseBVisible}
          userInfo={userInfo}
          groupMember={groupMember}
        />:null}

        {hasUserVisible?<HasUser
           {...hasUserMethods}
           hasUserVisible={hasUserVisible}
           groupMember={groupMember}
        />:null}

        <ChoosePerson
            {...BindUserMethods}
            bindUserVisible={bindUserVisible}
            treeDataList={treeDataList}
            personData={orgDataList}
            text={userInfo}
          />
        {menuTreeData && authorizeModalVisible ? <AuthorizeList
          {...authorizeMethods}
          authorizeModalVisible={authorizeModalVisible}
          menuTreeData={menuTreeData}
          text={text}
        /> : null}

      </PageHeaderWrapper>
    );
  }
}

//菜单授权modal
class AuthorizeList extends PureComponent {
  state = {
    selectedRow: [],
    handleCheck: false,
  };

  okHandle = () => {
    const {menuRight, text, handleAuthorizeModalVisible} = this.props;
    const {selectedRow, handleCheck} = this.state;
    let menuIdList;
    if (!handleCheck) {
      menuIdList = !selectedRow.length ? text.menuIdList : selectedRow.join(",");
    } else {
      menuIdList = selectedRow.join(",");
    }

    // if(!menuIdList){
    //     message.error('请选择菜单');
    //   return
    // }
    const params = {
      roleId: text.id,
      menuIdList,
    }
    menuRight(params);
    handleAuthorizeModalVisible();
  };

  onCheck = (info) => {
    this.setState({
      selectedRow: info,
      handleCheck: true,
    })
  }

  render() {
    const {authorizeModalVisible, handleAuthorizeModalVisible, menuTreeData, text} = this.props;
    const {selectedRow} = this.state;

    const loop = data => data.map((item) => {
      if (item.children) {
        return (
          <TreeNode key={item.id} title={item.name} {...item}>
            {loop(item.children || [])}
          </TreeNode>
        );
      }
      return <TreeNode key={item.id} title={item.name} {...item}/>;
    });

    return (
      <Modal
        destroyOnClose
        width={640}
        title='菜单授权'
        visible={authorizeModalVisible}
        onOk={this.okHandle}
        onCancel={() => handleAuthorizeModalVisible()}
        maskClosable={false}
      >
        <h4>角色名称：{text && text.roleName}</h4>
        {menuTreeData && menuTreeData.length ? <Tree
          checkable
          defaultCheckedKeys={text && text.menuIdList ? text.menuIdList : ['']}
          multiple={false}
          defaultExpandedKeys={text && text.menuIdList ? text.menuIdList : ['']}
          onCheck={this.onCheck}
        >

          {loop(menuTreeData || [])}

        </Tree> : null}
      </Modal>
    );
  }
}

class ChooseButton extends PureComponent {
  okHandle = () => {
    const {groupMember, userInfo, bindUserRole} = this.props;
    // if(!(groupMember.length&&groupMember[0].userCode)){
    //   Modal.warning({title: '请至少选择一位人员'});
    //   return;
    // }
    const userCodeList = groupMember.map((v)=>{return v.userCode}).join(',');
    bindUserRole({roleId:userInfo.id,userCodeList});
  }

  render() {
    const { chooseBVisible, handChooseBVisible, handleHasUserVisible, groupMember, handleBindUserVisible } = this.props;
  return (
    <Modal
      destroyOnClose
      width={800}
      title="人员设置"
      visible={chooseBVisible}
      onCancel={() => handChooseBVisible()}
      onOk={this.okHandle}
      zIndex={999}
    >
      <FormItem labelCol={{ span: 4 }} wrapperCol={{ span: 18 }} label="人员设置">
        <Button type="primary" onClick={() => handleBindUserVisible(true)} >请选择</Button>
        <div>{groupMember&&groupMember.length?groupMember.slice(0,3).map((v,i) => {
        return <span key={i} style={{marginRight:'20px',}}>{v.userName} </span>
      }):null}{groupMember&&groupMember.length&&groupMember.length>3?'...':''}
      {groupMember&&groupMember.length&&groupMember.length>0?<a onClick={() => handleHasUserVisible(true)} style={{marginLeft:25}}>查看已选人员</a>:null}
      </div>
      </FormItem>
    </Modal>
  );
  }
}


export default RoleList;
